﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.IO;

//using Gateway01;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using ShoveEL.Alipay;

/// <summary>
/// Task 的摘要说明
/// </summary>
public class Task
{
    private long gCount1 = 0;

    private System.Threading.Thread thread;

    public int State = 0;   // 0 停止 1 运行中 2 置为停止
    
    public Task()
	{
	}

    public void Run()
    {
        if (ShoveEL._Web.WebConfig.GetAppSettingsBool("DEBUG", false))
        {
            return;
        }

        // 已经启动
        if (State == 1)
        {
            return;
        }

        lock (this) // 确保临界区被一个 Thread 所占用
        {
            State = 1;

            gCount1 = 0;

            thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do));
            thread.IsBackground = true;

            thread.Start();

            PublicFunction.WriteLogini("Task Start.");
        }
    }

    public void Exit()
    {
        State = 2;
    }

    public void Do()
    {
        while (true)
        {
            if (State == 2)
            {
                State = 0;
                thread = null;

                return;
            }

            System.Threading.Thread.Sleep(1000);   // 1秒为单位

            gCount1++;

            #region 3 小时, 下载派款结果分析结果

            if (gCount1 >= (60 * 60) * 3)
            //if (gCount1 >= 1)
            {
                gCount1 = 0;

                try
                {
                    DownLoadResult();                    
                }
                catch { }
            }

            #endregion

        }
    }

    #region 定时器执行的事件

    private void DownLoadResult()	//下载结果
    {
        //业务参数赋值；
        string partner = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_UserNumber", "");		//partner		合作伙伴ID			保留字段
        string key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码

        string gateway = "https://www.alipay.com/cooperate/gateway.do";
        string service = "bptb_result_file";
        string sign = "";
        string _input_charset = "GB2312";                                                  //编码类型
        string biz_type = "d_sale";                                                        //业务类型

        Alipay ap = new Alipay();

        DateTime Now = DateTime.Now;
        int NowToInt = Now.Year * 10000 + Now.Month * 100 + Now.Day;

        //DataTable dt = DAL.Tables.T_PaymentFiles.Select("", "Result = 0 and dbo.F_DateTimeToInt([DateTime]) < " + NowToInt.ToString(), ""); //语句未优化
        DataTable dt = ShoveEL.Database.MSSQL.Select("select max([DateTime]) as [DateTime] from T_PaymentFiles where Result = 0 and dbo.F_DateTimeToInt([DateTime]) < dbo.F_DateTimeToInt(getdate()) group by dbo.F_DateTimeToInt([DateTime])");

        if (dt == null)
        {
            //写日志，下载支付宝派款结果时，任务执行数据库连接错误

            return;
        }
        
        foreach (DataRow dr in dt.Rows)
        {
            string fileName = "";
            DateTime time = ShoveEL._Convert.StrToDateTime(dr["DateTime"].ToString(), DateTime.Now.ToShortDateString());

            //fileName = "result" + dr["FileName"].ToString();
            //fileName = fileName.Substring(0, fileName.IndexOf("."));
            fileName = "result" + time.ToString("yyyyMMdd");

            //string ContentType = "application/octet-stream";
            // 生成需要上传的二进制数组        
            CreateBytes cb = new CreateBytes();
            // 所有表单数据
            ArrayList bytesArray = new ArrayList();
            // 普通表单
            string[] Sortedstr = ap.GetDownloadParams
                (
                service,
                _input_charset,
                partner,
                biz_type
                );

            string[] downFields = new string[Sortedstr.Length + 1];
            int i = 0;

            char[] delimiterChars = { '=' };

            for (i = 0; i < Sortedstr.Length; i++)
            {
                string fieldName = Sortedstr[i].Split(delimiterChars)[0];
                string fieldValue = Sortedstr[i].Split(delimiterChars)[1];

                bytesArray.Add(cb.CreateFieldData(fieldName, fieldValue));
                downFields[i] = fieldName + "=" + fieldValue;
            }
            
            string date = time.ToString("yyyyMMdd");
            bytesArray.Add(cb.CreateFieldData("date", date));
            downFields[i] = "date" + "=" + date;
            sign = AlipayCommon.GetSign(downFields, key).Trim();
            bytesArray.Add(cb.CreateFieldData("sign", sign));
            bytesArray.Add(cb.CreateFieldData("sign_type", "MD5"));

            // 合成所有表单并生成二进制数组
            byte[] bytes = cb.JoinBytes(bytesArray);

            // 返回的内容
            byte[] responseBytes;

            // 上传到指定Url
            bool uploaded = cb.UploadData(gateway, bytes, out responseBytes);

            string DownLoadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "AlipayPayment\\RESULT\\";
            //判断responseByte是否以PK开头(以PK开头说明可以下载)
            if (responseBytes[0] == 80 && responseBytes[1] == 75)
            {
                //判断文件是否存在
                if (System.IO.Directory.Exists(DownLoadFolder))//存在
                {
                    try
                    {
                        if (File.Exists(DownLoadFolder + fileName + ".zip"))
                        {
                            File.Delete(DownLoadFolder + fileName + ".zip");
                        }

                        using (FileStream file = new FileStream(DownLoadFolder + fileName + ".zip", FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            file.Write(responseBytes, 0, responseBytes.Length);
                        }

                        UnZip(DownLoadFolder + fileName + ".zip", DownLoadFolder + fileName);

                        //读取CSV
                        int intColCount = 0;
                        bool blnFlag = true;
                        bool blnFlagDtDetail = true;
                        DataTable dtResult = new DataTable("TableName");

                        DataColumn dcResult;
                        DataRow drResult;

                        DataTable dtDetail = new DataTable("dtDetail");

                        DataColumn dcDetail;
                        DataRow drDetail;

                        string strpath = DownLoadFolder + fileName + "\\ALIPAY__RESULT.csv"; //cvs文件路径
                        string strline;
                        string[] aryline;

                        System.IO.StreamReader mysr = new System.IO.StreamReader(strpath, Encoding.GetEncoding("GB2312"));

                        int y = 0;
                        while ((strline = mysr.ReadLine()) != null)
                        {
                            aryline = strline.Split(new char[] { ',' });

                            if (y < 2)
                            {
                                if (blnFlag)
                                {
                                    blnFlag = false;
                                    intColCount = aryline.Length;
                                    for (int j = 0; j < aryline.Length; j++)
                                    {
                                        dcResult = new DataColumn(aryline[j]);
                                        dtResult.Columns.Add(dcResult);
                                    }
                                }

                                if (y != 0)
                                {
                                    drResult = dtResult.NewRow();
                                    for (int j = 0; j < intColCount; j++)
                                    {
                                        drResult[j] = aryline[j];
                                    }
                                    dtResult.Rows.Add(drResult);
                                }
                            }
                            else
                            {
                                if (blnFlagDtDetail)
                                {
                                    blnFlagDtDetail = false;
                                    intColCount = aryline.Length;
                                    for (int j = 0; j < aryline.Length; j++)
                                    {
                                        dcDetail = new DataColumn(aryline[j]);
                                        dtDetail.Columns.Add(dcDetail);
                                    }
                                }

                                if (y != 2)
                                {
                                    drDetail = dtDetail.NewRow();
                                    for (int j = 0; j < intColCount; j++)
                                    {
                                        try
                                        {
                                            drDetail[j] = aryline[j];
                                        }
                                        catch
                                        {
                                            drDetail[j] = "";
                                        }
                                    }
                                    dtDetail.Rows.Add(drDetail);
                                }
                            }

                            y++;
                        }

                        foreach (DataRow drdtDetail in dtDetail.Rows)
                        {
                            string CSVFile = drdtDetail[0].ToString();
                            CSVFile = CSVFile.Substring(0, CSVFile.IndexOf(".")) + ".zip".ToLower();

                            if ((drdtDetail[1].ToString() == "已处理") && (drdtDetail[8].ToString() == "处理完成"))
                            {
                                string FilePath = DownLoadFolder + fileName + "\\" + drdtDetail[0].ToString();

                                DataTable dtCSVDetail = GetDetail(FilePath);

                                foreach (DataRow drCSVDetail in dtCSVDetail.Rows)
                                {
                                    if (drCSVDetail[9].ToString().ToLower() == "s")
                                    {
                                        //支付成功，充入电子货币

                                    }
                                    else
                                    {
                                        //支付没有成功，返还会员提款的金额
                                        if (DAL.Procedures.P_PaymentDefeatOnlyOne.Call(ShoveEL._Convert.StrToLong(drCSVDetail[0].ToString(), -1), -20, 501) < 0)
                                        {
                                            PublicFunction.WriteLogini("P_PaymentDefeatOnlyOne 过程执行失败 2");

                                            continue;
                                        }
                                    }
                                }

                                ShoveEL.Database.MSSQL.ExecuteNonQuery("Update T_PaymentFiles set [Result] = 2 where  Lower([FileName]) = '" + CSVFile + "'");
                            }
                            else if (drdtDetail[1].ToString() == "处理中")
                            {
                                continue;
                            }
                            else
                            {
                                //文件格式错误的处理                                
                                try
                                {
                                    //支付没有成功，返还会员提款的金额
                                    if (DAL.Procedures.P_PaymentDefeat.Call(CSVFile, -20, 501) < 0)
                                    {
                                        PublicFunction.WriteLogini("P_PaymentDefeat 过程执行失败 2");

                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    PublicFunction.WriteLogini(ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PublicFunction.WriteLogini(ex.Message);
                    }
                }
                else//不存在
                {
                    //Response.Write("文件将被下载到C盘下的downloadResponse中，请您在C盘根目录下创建该文件");
                    continue;
                }
            }
            else
            {
                //Response.Write(System.Text.Encoding.Default.GetString(responseBytes));

                continue;
            }
        }
    }

    protected void DownloadRefoundResult()
    {
        //业务参数赋值；
        string partner = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_UserNumber", "");		//partner		合作伙伴ID			保留字段
        string key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码

        string gateway = "https://www.alipay.com/cooperate/gateway.do";
        string service = "bptb_refund_file";
        string sign_type = "MD5";
        string _input_charset = "GB2312";                                                  //编码类型
        string sign = "";
        string biz_type = "d_sale";                                                        //业务类型
        string agentID = "2088001456282873";

        Alipay ap = new Alipay();

        // 这部分需要完善
        //string ContentType = "application/octet-stream";
        string fileName = "";
        DateTime Now = DateTime.Now;
        int NowToInt = Now.Year * 10000 + Now.Month * 100 + Now.Day;

        DataTable dt = ShoveEL.Database.MSSQL.Select("select max([DateTime]) as [DateTime] from T_PaymentFiles where Result = 0 and dbo.F_DateTimeToInt([DateTime]) < dbo.F_DateTimeToInt(getdate()) group by dbo.F_DateTimeToInt([DateTime])");

        if (dt == null)
        {
            //写日志，下载支付宝派款结果时，任务执行数据库连接错误

            return;
        }

        foreach (DataRow dr in dt.Rows)
        {
            DateTime time = ShoveEL._Convert.StrToDateTime(dr["DateTime"].ToString(), DateTime.Now.ToShortDateString());

            //fileName = "result" + dr["FileName"].ToString();
            //fileName = fileName.Substring(0, fileName.IndexOf("."));
            fileName = "refound" + time.ToString("yyyyMMdd");

            // 生成需要上传的二进制数组        
            CreateBytes cb = new CreateBytes();
            // 所有表单数据
            ArrayList bytesArray = new ArrayList();
            // 普通表单
            string[] Sortedstr = ap.GetDownloadParams
                (
                service,
                _input_charset,
                partner,
                biz_type
                );

            string[] downFields = new string[Sortedstr.Length + 1];
            int i = 0;

            char[] delimiterChars = { '=' };

            for (i = 0; i < Sortedstr.Length; i++)
            {
                string fieldName = Sortedstr[i].Split(delimiterChars)[0];
                string fieldValue = Sortedstr[i].Split(delimiterChars)[1];

                bytesArray.Add(cb.CreateFieldData(fieldName, fieldValue));
                downFields[i] = fieldName + "=" + fieldValue;
            }

            string date = time.ToString("yyyyMMdd");
            //string date = "20080430";    //dptTime.ToString("yyyyMMdd");
            bytesArray.Add(cb.CreateFieldData("date", date));
            downFields[i] = "date" + "=" + date;
            sign = AlipayCommon.GetSign(downFields, key).Trim();
            bytesArray.Add(cb.CreateFieldData("sign", sign));
            bytesArray.Add(cb.CreateFieldData("sign_type", "MD5"));

            // 合成所有表单并生成二进制数组
            byte[] bytes = cb.JoinBytes(bytesArray);

            // 返回的内容
            byte[] responseBytes;

            // 上传到指定Url
            bool uploaded = cb.UploadData(gateway, bytes, out responseBytes);

            string DownLoadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "AlipayPayment\\REFOUND\\";

            if (responseBytes[0] == 80 && responseBytes[1] == 75)
            {
                //判断文夹件是否存在
                 if (System.IO.Directory.Exists(DownLoadFolder))//存在
                {
                    try
                    {
                        if (File.Exists(DownLoadFolder + fileName + ".zip"))
                        {
                            File.Delete(DownLoadFolder + fileName + ".zip");
                        }

                        using (FileStream file = new FileStream(DownLoadFolder + fileName + ".zip", FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            file.Write(responseBytes, 0, responseBytes.Length);
                        }

                        UnZip(DownLoadFolder + fileName + ".zip", DownLoadFolder + fileName);

                        //读取CSV

                        int intColCount = 0;
                        bool blnFlag = true;
                        bool blnFlagDtDetail = true;
                        DataTable dtResult = new DataTable("TableName");

                        DataColumn dcResult;
                        DataRow drResult;

                        DataTable dtDetail = new DataTable("dtDetail");

                        DataColumn dcDetail;
                        DataRow drDetail;

                        string strpath = DownLoadFolder + fileName + "\\ALIPAY__RESULT.csv"; //cvs文件路径
                        string strline;
                        string[] aryline;

                        System.IO.StreamReader mysr = new System.IO.StreamReader(strpath, Encoding.GetEncoding("GB2312"));

                        int y = 0;
                        while ((strline = mysr.ReadLine()) != null)
                        {
                            aryline = strline.Split(new char[] { ',' });

                            if (y < 2)
                            {
                                if (blnFlag)
                                {
                                    blnFlag = false;
                                    intColCount = aryline.Length;
                                    for (int j = 0; j < aryline.Length; j++)
                                    {
                                        dcResult = new DataColumn(aryline[j]);
                                        dtResult.Columns.Add(dcResult);
                                    }
                                }

                                if (y != 0)
                                {
                                    drResult = dtResult.NewRow();
                                    for (int j = 0; j < intColCount; j++)
                                    {
                                        drResult[j] = aryline[j];
                                    }
                                    dtResult.Rows.Add(drResult);
                                }
                            }
                            else
                            {
                                if (blnFlagDtDetail)
                                {
                                    blnFlagDtDetail = false;
                                    intColCount = aryline.Length;
                                    for (int j = 0; j < aryline.Length; j++)
                                    {
                                        dcDetail = new DataColumn(aryline[j]);
                                        dtDetail.Columns.Add(dcDetail);
                                    }
                                }

                                if (y != 2)
                                {
                                    drDetail = dtDetail.NewRow();
                                    for (int j = 0; j < intColCount; j++)
                                    {
                                        try
                                        {
                                            drDetail[j] = aryline[j];
                                        }
                                        catch
                                        {
                                            drDetail[j] = "";
                                        }
                                    }
                                    dtDetail.Rows.Add(drDetail);
                                }
                            }

                            y++;
                        }

                        foreach (DataRow drdtDetail in dtDetail.Rows)
                        {
                            string CSVFile = drdtDetail[0].ToString();
                            CSVFile = CSVFile.Substring(0, CSVFile.IndexOf(".")) + ".zip".ToLower();

                            if ((drdtDetail[1].ToString() == "已处理") && (drdtDetail[8].ToString() == "处理完成"))
                            {
                                string FilePath = DownLoadFolder + fileName + "\\" + drdtDetail[0].ToString();

                                DataTable dtCSVDetail = GetDetail(FilePath);

                                foreach (DataRow drCSVDetail in dtCSVDetail.Rows)
                                {
                                    if (drCSVDetail[9].ToString().ToLower() == "s")
                                    {
                                        //写入晓风统计
                                    }
                                    else
                                    {
                                        //支付没有成功，返还会员提款的金额
                                        if (DAL.Procedures.P_PaymentDefeatOnlyOne.Call(ShoveEL._Convert.StrToLong(drCSVDetail[0].ToString(), -1), -20, 501) < 0)
                                        {
                                            PublicFunction.WriteLogini("P_PaymentDefeatOnlyOne 过程执行失败 2");

                                            continue;
                                        }
                                    }
                                }

                                ShoveEL.Database.MSSQL.ExecuteNonQuery("Update T_PaymentFiles set [Result] = 1 where  Lower([FileName]) = '" + CSVFile + "'");
                            }
                            else if (drdtDetail[1].ToString() == "处理中")
                            {
                                continue;
                            }
                            else
                            {
                                //文件格式错误的处理                               
                                
                                try
                                {
                                    //支付没有成功，返还会员提款的金额
                                    if (DAL.Procedures.P_PaymentDefeat.Call(CSVFile, -20, 501) < 0)
                                    {
                                        PublicFunction.WriteLogini("P_PaymentDefeat 过程执行失败 2");

                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    PublicFunction.WriteLogini(ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PublicFunction.WriteLogini(ex.Message);
                    }
                }
                else//不存在
                {
                    //Response.Write("文件将被下载到C盘下的downloadResponse中，请您在C盘根目录下创建该文件");
                    continue;
                }
            }
            else
            {
                //Response.Write(System.Text.Encoding.Default.GetString(responseBytes));

                continue;
            }
        }
    }

    ///   <summary>   
    ///   解压缩   
    ///   </summary>   
    ///   <param   name="FilePath"></param>   
    private void UnZip(string FilePath, string OutputFolder)
    {
        if (!File.Exists(FilePath))
        {
            throw new FileNotFoundException("File:" + FilePath + "   Not   Found.");
        }

        FileInfo fi = new FileInfo(FilePath);
        using (ZipInputStream stream = new ZipInputStream(fi.OpenRead()))
        {
            string FolderName = null;

            if (string.IsNullOrEmpty(OutputFolder))
            {
                FolderName = fi.FullName.Replace(fi.Extension, string.Empty);
            }
            else
            {
                FolderName = OutputFolder;  // fi.Name;
            }

            //首先为该文件创建一个解压缩到的目录   
            Directory.CreateDirectory(FolderName);

            ZipEntry FileName = null;
            while ((FileName = stream.GetNextEntry()) != null)
            {
                int size = 2048;
                byte[] data = new byte[2048];

                string[] s = FileName.Name.Split('\\');
                if (s.Length > 1)
                {
                    StringBuilder sb = new StringBuilder(FolderName);

                    int i = 0;
                    while (i < s.Length - 1)
                    {
                        sb.Append('\\');
                        sb.Append(s[i++]);
                    }

                    Directory.CreateDirectory(sb.ToString());
                }

                string outfile = FolderName + "\\" + FileName.Name;

                using (FileStream fs = new FileStream(outfile, FileMode.Create))
                {

                    while (true)
                    {
                        size = stream.Read(data, 0, data.Length);

                        if (size > 0)
                        {
                            fs.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }

                    fs.Flush();
                    fs.Close();
                }
            }
        }
    }

    /// <summary>
    /// 获取CSV的数据
    /// </summary>
    /// <param name="FilePath"></param>
    /// <returns></returns>
    private DataTable GetDetail(string FilePath)
    {
        int intColCount = 0;
        bool blnFlag = true;
        bool blnFlagDtDetail = true;
        DataTable dtResultCSV = new DataTable("dtCSV");

        DataColumn dcResultCSV;
        DataRow drResultCSV;

        DataTable dtDetailCSV = new DataTable("dtCSVDetail");

        DataColumn dcDetailCSV;
        DataRow drDetailCSV;

        string strline;
        string[] aryline;

        System.IO.StreamReader mysr = new System.IO.StreamReader(FilePath, Encoding.GetEncoding("GB2312"));

        int y = 0;
        while ((strline = mysr.ReadLine()) != null)
        {
            aryline = strline.Split(new char[] { ',' });

            if (y < 2)
            {
                //if (blnFlag)
                //{
                //    blnFlag = false;
                //    intColCount = aryline.Length;
                //    for (int j = 0; j < aryline.Length; j++)
                //    {
                //        dcResultCSV = new DataColumn(aryline[j]);
                //        dtResultCSV.Columns.Add(dcResultCSV);
                //    }
                //}

                //if (y != 0)
                //{
                //    drResultCSV = dtResultCSV.NewRow();
                //    for (int j = 0; j < intColCount; j++)
                //    {
                //        drResultCSV[j] = aryline[j];
                //    }
                //    dtResultCSV.Rows.Add(drResultCSV);
                //}
            }
            else
            {
                if (blnFlagDtDetail)
                {
                    blnFlagDtDetail = false;
                    intColCount = aryline.Length;
                    for (int j = 0; j < aryline.Length; j++)
                    {
                        dcDetailCSV = new DataColumn(aryline[j]);
                        dtDetailCSV.Columns.Add(dcDetailCSV);
                    }
                }

                if (y != 2)
                {
                    drDetailCSV = dtDetailCSV.NewRow();
                    for (int j = 0; j < intColCount; j++)
                    {
                        try
                        {
                            drDetailCSV[j] = aryline[j];
                        }
                        catch
                        {
                            drDetailCSV[j] = "";
                        }
                    }
                    dtDetailCSV.Rows.Add(drDetailCSV);
                }
            }

            y++;
        }

        return dtDetailCSV;
    }

    #endregion
}
